package com.xsz.pda.device.nfc;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;

import com.blankj.utilcode.util.ToastUtils;

import java.util.Locale;

// TypeA卡读取
public class NFCReader {


    public static interface OnReadListener{
        void OnRead(String id);
    }

    private NfcAdapter nfcAdapter;
    private PendingIntent pendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private Context context;
    private boolean isNew = true;

    private int selector = 0;
    private int block = 0;

    private OnReadListener onReadListener;

    private static final String TAG = "IOException";

    public NFCReader(Context context){
        this.context = context;
        nfcAdapter = NfcAdapter.getDefaultAdapter(context);
        if (!nfcAdapter.isEnabled()) {
            ToastUtils.showLong("请打开NFC");
            return;
        }
        Intent intent = new Intent(context, context.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_MUTABLE);
//        pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context,
//                context.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        ndef.addCategory("*/*");
        mFilters = new IntentFilter[] { ndef };// 过滤器
        mTechLists = new String[][] {
                new String[] { MifareClassic.class.getName() },
                new String[] { NfcA.class.getName() } };// 允许扫描的标签类型
    }


    public void setOnReadListener(OnReadListener onReadListener) {
        this.onReadListener = onReadListener;
    }


    // 在 onResume 中 调用
    public void touch(){
        Activity activity = ((Activity)context);
        nfcAdapter.enableForegroundDispatch((Activity) context, pendingIntent, mFilters,
                mTechLists);
        if (isNew) {
            Intent intents = activity.getIntent();
            if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intents.getAction())) {
                // 处理该intent
                processIntent(intents);
                isNew = false;
            }
        }
    }

    // 在 onNewIntent 中调用
    public void parse(Intent intent){
        // 得到是否检测到ACTION_TECH_DISCOVERED触发
        // nfcAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,
        // mTechLists);
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            // 处理该intent
            processIntent(intent);
        }
    }

    /**
     * 读取NFC信息数据
     *
     * @param intent
     */
    private void processIntent(Intent intent) {

        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
//        //    var constantSecret = "BC0123456AD7"
//        byte[] key = {(byte) 0xBC, (byte) 0x01, (byte) 0x23, (byte) 0x45, (byte) 0x6A, (byte) 0xD7};
//
//        MifareClassic mfc = MifareClassic.get(tag);
//
//        try {
//            mfc.connect();
//            //获取扇区数量
//
//            boolean isPassword = mfc.authenticateSectorWithKeyA(selector, key);
//            if (isPassword) {
//                Log.e(TAG, "密码正确");
//                StringBuilder metaInfo = new StringBuilder();
//                int bCount = mfc.getBlockCountInSector(selector);
//                int bIndex = mfc.sectorToBlock(selector);
//                byte[] data = mfc.readBlock(0);
//                byte[] uidbyte = new byte[4];
//                System.arraycopy(data, 0, uidbyte, 0, 4);
//                String uid = new String(uidbyte);
//                String tagUid = bytesToHexString(tag.getId());
////                9D016a6B64C08040002EA7ED872544C1D
////                9D0166B6
//                Log.e(TAG, uid);
//            }
//        } catch (IOException e) {
//            Log.e(TAG, e.getMessage(), e);
//        }
        if (onReadListener!=null){
            onReadListener.OnRead(bytesToHexString(tag.getId()));
        }
    }


    // 字符序列转换为16进制字符串
    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
            buffer[1] = Character.forDigit(src[i] & 0x0F, 16);

            stringBuilder.append(buffer);

        }
        return stringBuilder.toString().toUpperCase(Locale.ROOT);
    }

}

//    byte[] key = {(byte) 0xA0, (byte) 0xB7, (byte) 0xA5, (byte) 0xC5, (byte) 0x80, (byte) 0x88};
//    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
//    //加密IC卡
//    MifareClassic mifareClassic = MifareClassic.get(tag);
//mifareClassic.connect();
////获取扇区数量
//        int count = mifareClassic.getSectorCount();
////判断是否为默认密码
//        boolean isOpen = mifareClassic.authenticateSectorWithKeyA(1, MifareClassic.KEY_DEFAULT);
//        if (isOpen) {
//        //加密
//        int bCount = mifareClassic.getBlockCountInSector(1);
//        int bIndex = mifareClassic.sectorToBlock(1);
//        for (int j = 0; j < bCount; j++) {
//        //修改KeyA和KeyB
//        if ((bIndex + j) == 7) {
//        mifareClassic.writeBlock(bIndex + j, new byte[]{(byte) 0xa0, (byte) 0xb7, (byte) 0xa5, (byte) 0xc5, (byte) 0x80, (byte) 0x88, (byte) 0xff, 0x07, (byte) 0x80, (byte) 0x69, (byte) 0xa0, (byte) 0xb7, (byte) 0xa5, (byte) 0xc5, (byte) 0x80, (byte) 0x88});
//
//        }
//        }
//        } else {
//        //解密
//        boolean isPassword = mifareClassic.authenticateSectorWithKeyA(1, key);
//        if (isPassword) {
//        Log.e("onNewIntent:", "密码正确");
//
//        }